package com.zqh.myfmmall.controller;



import com.zqh.myfmmall.entity.ProductSku;
import com.zqh.myfmmall.entity.ShoppingCart;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.service.ProductSkuService;
import com.zqh.myfmmall.service.ShoppingCartService;
import com.zqh.myfmmall.utils.JwtUtil;
import com.zqh.myfmmall.vo.ShoppingCartVO;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车 (ShoppingCart)表控制层
 *
 * @author KONO 曾淇杭哒！
 * @since 2022-01-20 20:53:00
 */
@RestController
@RequestMapping("shoppingCart")
@Api(tags = "购物车管理")
public class ShoppingCartController{
    /**
     * 服务对象
     */
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private ProductSkuService productSkuService;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("list")
    public Result listShoppingCart(){
        String token = request.getHeader("token");
        String userId = JwtUtil.getClaim(token).get("userId", String.class);
        List<ShoppingCartVO> shoppingCartVOS = shoppingCartService.getVosByUserId(userId);
        return Result.success(shoppingCartVOS);
    }

    @GetMapping("getByIds")
    public Result getByIds(@RequestParam("shoppingCartIds") List<String> ids){
        List<ShoppingCartVO> shoppingCartVos = shoppingCartService.getVosByCartIds(ids);
        return Result.success(shoppingCartVos);
    }

    @PostMapping("add")
    public Result addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        String token = request.getHeader("token");
        String userId = JwtUtil.getClaim(token).get("userId", String.class);
        shoppingCart.setUserId(userId);
        ProductSku sku = productSkuService.query().eq("sku_id", shoppingCart.getSkuId()).select("sell_price").one();
        shoppingCart.setAddedPrice(sku.getSellPrice());
        boolean save = shoppingCartService.save(shoppingCart);
        if (save) {
            return Result.success("添加购物车成功");
        }
        return Result.fail("添加购物车失败");
    }

    @PutMapping
    public Result updateShoppingCart(@RequestBody ShoppingCart shoppingCart){
        boolean success = shoppingCartService.updateById(shoppingCart);
        if (success){
            return Result.success("修改购物车成功");
        }
        return Result.fail("修改购物车失败");
    }

    @DeleteMapping
    public Result deleteShoppingCart(@RequestParam String cartId){
        boolean success = shoppingCartService.removeById(cartId);
        if (success){
            return Result.success("删除购物车成功");
        }
        return Result.fail("删除购物车失败");
    }


}

